# location_service.py
# 运行前：pip install flask flask-cors

from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
import socket

app = Flask(__name__)
CORS(app)  # 开发方便，允许跨域。生产请配置白名单。

HTML_PAGE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <title>获取当前位置示例</title>
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; }
    pre { background:#f7f7f7; padding:10px; border-radius:6px; white-space: pre-wrap; word-wrap:break-word; }
    .info { margin-top:10px; }
    button { padding: 10px 14px; font-size: 16px; }
  </style>
</head>
<body>
  <h2>获取当前位置（仅第一步：读取经纬）</h2>
  <p>点击下方按钮，浏览器会请求定位权限，允许后显示结果并上报到服务器。</p>
  <button id="btn">获取位置并上报</button>
  <div class="info">
    <h3>结果</h3>
    <pre id="result">尚未获取</pre>
  </div>

  <script>
    const btn = document.getElementById('btn');
    const out = document.getElementById('result');

    function show(obj) {
      out.textContent = JSON.stringify(obj, null, 2);
    }

    btn.addEventListener('click', () => {
      if (!navigator.geolocation) {
        alert('浏览器不支持 geolocation');
        return;
      }

      navigator.geolocation.getCurrentPosition(successHandler, errorHandler, {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 0
      });
    });

    async function successHandler(position) {
      const coords = position.coords;
      const data = {
        latitude: coords.latitude,
        longitude: coords.longitude,
        accuracy_m: coords.accuracy,
        altitude: coords.altitude,
        altitudeAccuracy: coords.altitudeAccuracy,
        heading: coords.heading,
        speed: coords.speed,
        timestamp: position.timestamp
      };

      show({
        ok: true,
        message: '已获取到位置信息（WGS-84）',
        data
      });

      try {
        const resp = await fetch('/report_location', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data),
          credentials: 'omit'
        });
        const j = await resp.json();
        console.log('server reply:', j);
      } catch (e) {
        console.error('上报失败', e);
      }
    }

    function errorHandler(err) {
      const msg = { ok: false, code: err.code, message: err.message };
      show(msg);
      console.error('定位错误:', err);
      alert('定位失败：' + err.message);
    }
  </script>
</body>
</html>
"""

@app.route("/", methods=["GET"])
def index():
    return render_template_string(HTML_PAGE)

@app.route("/report_location", methods=["POST"])
def report_location():
    data = request.get_json(force=True)
    # 简单打印到控制台（你可以改为保存到 DB、转发到内网服务等）
    print("=== Received location ===")
    print(data)
    print("=========================")
    # 如果你需要将来转发到内网服务，可在这里实现 requests.post(...)
    return jsonify({"ok": True, "received": data}), 200

def get_local_ip():
    # 获取本机在局域网的 IP（用于提示访问地址）
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # 不真正发送数据，只用来获得本机对外路由使用的地址
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    except Exception:
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip

if __name__ == "__main__":
    host = "0.0.0.0"
    port = 5000
    local_ip = get_local_ip()
    print(f"Service starting. Open the page on this machine: http://127.0.0.1:{port}/")
    print(f"Or open from other devices on same LAN: http://{local_ip}:{port}/")
    print("If the phone is on the same Wi-Fi, open that URL in the phone browser.")
    app.run(host=host, port=port, debug=True)
